package com.ldgame.gfx;

import static org.lwjgl.opengl.GL11.*;

import java.io.IOException;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.util.vector.Vector3f;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;

public class Screen {
	private static int width;
	private static int height;
	private static Texture gameTexture;
	private Vector3f camPosition = new Vector3f();

	public Screen(int width, int height) {
		Screen.width = width;
		Screen.height = height;
	}
	
	static public int getWidth() {
		return width;
	}
	
	static public int getHeight() {
		return height;
	}
	
	public Vector3f getCamPosition() {
		return camPosition;
	}

	public void setCamPosition(Vector3f camPosition) {
		this.camPosition = camPosition;
	}
	
	public void init() {
		try {
			Display.setDisplayMode(new DisplayMode(width, height));
			Display.setInitialBackground(0.0f, 0.0f, 0.0f);
			Display.create();
		} catch (LWJGLException e) {
			e.printStackTrace();
			System.exit(0);
		}
		
		initStates();
		initTextures();
		enableGameTexture();
		setCamera();
	}
	
	private void initStates() {
		glEnable(GL_TEXTURE_2D);
		glEnable(GL_BLEND);
		glEnable(GL_CULL_FACE);
		glEnable(GL_COLOR_MATERIAL);
		glShadeModel(GL_SMOOTH);
		glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
		glViewport(0, 0, width, height);
	}
	
	private void initTextures() {
		try {
			gameTexture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("com/res/texture.png"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void enableGameTexture() {
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glBindTexture(GL_TEXTURE_2D, gameTexture.getTextureID());
	}
	
	public void renderStart() {
		Display.update();
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	}
	
	public boolean isClosed() {
		return Display.isCloseRequested();
	}
	
	public void destroy() {
		Display.destroy();
	}
	
	private void setCamera() {
		glPushMatrix();
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		glOrtho(0.0f, 800.0f, 600.0f, 0.0f, 0.0f, 1.0f);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
	}
}
